<?php

namespace App\Jobs;

use App\Models\Qh_LitQuestion;
use App\Models\Qh_Question;
use App\Models\User;
use App\Models\UserHistoryLearnQuestionCount;
use App\Service\Redis\RedisBaseService;
use Carbon\Carbon;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldBeUnique;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use Illuminate\Support\Facades\DB;
use Throwable;

class UserQuestionLearnLogDeleteJob implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

    protected int $userId;
    protected array $questionIds;
    /**
     * Create a new job instance.
     *
     * @return void
     */
    public function __construct($userId, $questionIds)
    {
        $this->userId = $userId;
        $this->questionIds = $questionIds;
    }

    /**
     * Execute the job.
     *
     * @return void
     * @throws Throwable
     */
    public function handle()
    {
        $litQuestionIds = DB::table('qh_lit_questions')->whereIn('parentId', $this->questionIds)->pluck('id')->toArray();
        $_litQuestionIds = [];
        foreach ($litQuestionIds as $lid) {
            $_litQuestionIds[] = intval('999999'.$lid);
        }

        \DB::transaction(function () use ($_litQuestionIds) {
            try {
                // 获取答题日志

                $correctCount = 0;
                $wrongCount = 0;
                $correctQuestionCountOfToday = 0;
                $wrongQuestionCountOfToday = 0;

                $logs = Db::table('qh_user_question_logs')->where('userId', $this->userId)->whereIn('questionId', $this->questionIds)->get();
                foreach ($logs as $log) {
                    $question = DB::table('qh_questions')->find($log->questionId);
                    if (!$question) continue;
                    $update = [];
                    // 更新正确次数
                    if ($log->result == 1) {
                        $correctCount += 1;
                        if ($log->created_at != null && Carbon::make($log->created_at)->isToday()) $correctQuestionCountOfToday += 1;
                        $update = ['rightCount' => $question->rightCount - 1];
                    }
                    // 更新错误次数
                    if ($log->result == 2) {
                        $wrongCount += 1;
                        if ($log->created_at != null && Carbon::make($log->created_at)->isToday()) $wrongQuestionCountOfToday += 1;
                        $update = ['wrongCount' => $question->wrongCount - 1];
                    }
                    DB::table('qh_questions')->where('id', $question->id)->update($update);
                }
                // 删除答题日志
                Db::table('qh_user_question_logs')->where('userId', $this->userId)->whereIn('questionId', $this->questionIds)->delete();

                // ------------------------  小题处理  -----------------------

                $logs = Db::table('qh_user_question_logs')->where('userId', $this->userId)->whereIn('questionId', $_litQuestionIds)->get();
                foreach ($logs as $log) {
                    $question = DB::table('qh_lit_questions')->find($log->questionId);
                    if (!$question) continue;

                    // 更新正确次数
                    if ($log->result == 1) {
                        $update = ['rightCount' => $question->rightCount -1];
                    }
                    // 更新错误次数
                    if ($log->result == 2) {
                        $update = ['wrongCount' => $question->wrongCount -1];
                    }
                    DB::table('qh_questions')->where('id', $question->id)->update($update);
                }
                // 删除小题答题日志
                Db::table('qh_user_question_logs')->where('userId', $this->userId)->whereIn('questionId', $_litQuestionIds)->delete();

                $sumCount = $correctCount + $wrongCount;
                // 记录日志
                UserHistoryLearnQuestionCount::create([
                    'userId' => $this->userId,
                    'reason' => '用户重做',
                    'allCount' => $sumCount,
                    'correctCount' => $correctCount,
                    'wrongCount' => $wrongCount
                ]);

                // 清空用户的答题数量统计
                $user = User::find($this->userId);
                $user->learnQuestionCount -= ($user->learnQuestionCount >= $sumCount ? $sumCount : $user->learnQuestionCount); // 刷题总量
                $user->correctQuestionCount -= ($user->correctQuestionCount >= $correctCount ? $correctCount : $user->correctQuestionCount);
                $user->wrongQuestionCount -= ($user->wrongQuestionCount >= $wrongCount ? $wrongCount : $user->wrongQuestionCount);
                $user->learnQuestionCountOfToday -= ($user->learnQuestionCountOfToday >= $sumCount ? $sumCount : $user->learnQuestionCountOfToday); // 今日刷题总量
                $user->correctQuestionCountOfToday -= ($user->correctQuestionCountOfToday >= $correctQuestionCountOfToday ? $correctQuestionCountOfToday : $user->correctQuestionCountOfToday);
                $user->wrongQuestionCountOfToday -= ($user->wrongQuestionCountOfToday >= $wrongQuestionCountOfToday ? $wrongQuestionCountOfToday : $user->wrongQuestionCountOfToday);
                $user->save();

                // 清空统计缓存
                $redisBaseService = new RedisBaseService();
                $redisBaseService->delUserStatisticsData('statistics:userLearnQuestionCount', $this->userId);
                $redisBaseService->delUserStatisticsData('statistics:userLearnQuestionOfTodayCount', $this->userId);
                $redisBaseService->delUserStatisticsData('statistics:userWrongQuestionCount', $this->userId);
                $redisBaseService->delUserStatisticsData('statistics:userCorrectQuestionCount', $this->userId);
                $redisBaseService->delUserStatisticsData('statistics:userCorrectQuestionCountOfToday', $this->userId);
                $redisBaseService->delUserStatisticsData('statistics:userWrongQuestionCountOfToday', $this->userId);

            }catch (\Exception $e) {
                \Log::debug('[重做]删除单题记录失败');
                \Log::error($e);
            }
        });
    }
}
